<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

class MY_Model extends CI_Model {

    protected $table;

    public function __construct() {
        parent::__construct();
        $this->load->database();
    }

    public function total($conditions = array()) {
        if (!empty($conditions)) {
            foreach ($conditions as $condition) {
                $this->db->where($condition[0], $condition[1]);
            }
        }

        return $this->db->count_all_results($this->table);
    }

    public function records($limit = 0, $offset = 0, $conditions = array()) {
        $this->db->from($this->table);

        if (!empty($conditions)) {
            foreach ($conditions as $condition) {
                $this->db->where($condition[0], $condition[1]);
            }
        }

        if ($limit) {
            $this->db->limit($limit, $offset);
        }

        $query = $this->db->get();

        return $query->result();
    }

    public function find($conditions) {
        if (is_numeric($conditions) || is_string($conditions)) {
            $rows = $this->records(1, 0, array(array('id', intval($conditions))));
        }

        if (is_array($conditions)) {
            $rows = $this->records(1, 0, $conditions);
        }

        return empty($rows) ? false : $rows[0];
    }

    public function insert($data) {
        $this->db->insert($this->table, $data);
        return $this->db->insert_id();
    }

    public function update($id, $data) {
        return $this->db->update($this->table, $data, array('id' => $id));
    }

    public function delete_batch($ids) {
        $this->db->where_in('id', $ids);

        return $this->db->delete($this->table);
    }

    public function delete($id) {
        return $this->db->delete($this->table, array('id' => intval($id)));
    }

}

